let express = require("express");
let path = require("path");

let app = express();
//处理body请求体的中间件
app.use(express.urlencoded());
app.use(express.json());

//处理跨域的中间件
app.use((request,response,next)=>{
  //全部允许跨域
// response.set("Access-Control-Allow-Origin", "*")
//设置允许跨域的ip
  // res.set("Access-Control-Allow-Origin", "http://127.0.0.1:57558")

  //设置允许跨域的地址集合
  let allowori = ["http://127.0.0.1:5500", "http://127.0.0.1:1010", "http://127.0.0.1:57557", "http://127.0.0.1:57558"]
  console.log(request.headers.origin);//拿到请求的来源地址
  if (allowori.includes(request.headers.origin)) {
    response.set('Access-Control-Allow-Origin',request.headers.origin)
    response.set('Access-Control-Allow-Headers','*')
  }
  next()
})

//cors跨域
app.get('/userinfo',(request, response) => {
  response.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男"
    }
  })
})

//jsonp请求接口
app.get("/get", (request, response) => {
  console.log(request.query);
  let { userid, cb } = request.query;
  let data = {
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男",
    },
  };
  response.send(`${cb}(${JSON.stringify(data)})`)
});

//查询信息的接口
app.get("/user", (request, response) => {
  let token = request.headers.token;
  console.log(token, "token");
  if (!token) {
    return response.send({
      code: 10002,
      msg: "无对应权限",
      data: null,
    });
  }

  let { userid } = request.query;

  //查询失败的情况
  if (userid !== "001") {
    return response.send({
      code: 10001,
      msg: "查询失败",
      data: null,
    });
  }

  //查询成功 响应
  response.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男",
    },
  });
});

//定义一个延迟响应的请求接口
app.get("/userdelay", (request, response) => {
  setTimeout(() => {
    let token = request.headers.token;
    console.log(token, "token");
    if (!token) {
      return response.send({
        code: 10002,
        msg: "无对应权限",
        data: null,
      });
    }

    let { userid } = request.query;

    //查询失败的情况
    if (userid !== "001") {
      return response.send({
        code: 10001,
        msg: "查询失败",
        data: null,
      });
    }

    //查询成功 响应
    response.send({
      code: 10000,
      msg: "查询成功",
      data: {
        name: "李博",
        age: 18,
        sex: "男",
      },
    });
  }, 2000);
});

app.listen(1010, () => {
  console.log("running");
});
